import propsTypes from 'proptypes';
import React, { Context } from 'react';

class ProviderDemo extends React.Component {
  static childContextTypes: { theme: any };
  // 提供者
  getChildContext() {
    const theme = {
      color: '#000',
      background: '#f40',
    };
    return { theme };
  }
  render() {
    return (
      <div>
        父组件的提供者
        <Son />
      </div>
    );
  }
}

// 老版本的需要使用 propsTypes 提供类型申明
ProviderDemo.childContextTypes = {
  theme: propsTypes.object,
};

// 消费者

// 消费者
class ConsumerDemo extends React.Component {
  static contextTypes: { theme: any };
  render() {
    console.log((this.context as any).theme); // {  color:'#ccc',  bgcolor:'pink' }
    const { color, background } = (this.context as any).theme;
    return <div style={{ color, background }}>消费者</div>;
  }
}

ConsumerDemo.contextTypes = {
  theme: propsTypes.object,
};

const Son = () => <ConsumerDemo />;

export default ProviderDemo;
